import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sweet_app/bloc/application_bloc.dart';
import 'package:sweet_app/bloc/bloc_provider.dart';
import 'package:sweet_app/buttons/loading_button.dart';
import 'package:sweet_app/buttons/simple_round_button.dart';
import 'package:sweet_app/http/api.dart';
import 'package:sweet_app/model/user.dart';
import 'package:sweet_app/utils/utils.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final scaffoldKey = GlobalKey<ScaffoldState>();
  final formKey = GlobalKey<FormState>();
  String _phone;
  String _password;
  bool _flag = false;
  bool _loading = false;

  void _submit(ApplicationBloc appBloc) async {
    print("submit");
    if (!_flag) {
      setState(() {
        _flag = true;
      });
    }
    final form = formKey.currentState;

    if (form.validate()) {
      form.save();
      setState(() {
        _loading = true;
      });
      ResultModel resultModel = await Api.login(phone: _phone, password:  _password);
      setState(() {
        _loading = false;
      });
      if(resultModel.type == ResultType.success) {
        await appBloc.saveUserInfo(User.fromJson(resultModel.data['user']), resultModel.data['token']);
        appBloc.addEvent(AppEvent.home);
      } else {
        showModel(context, resultModel.error);
      }
    }
  }


  @override
  Widget build(BuildContext context) {
    final ApplicationBloc appBloc = BlocProvider.of<ApplicationBloc>(context);
    double height = MediaQuery.of(context).size.height;
    return Scaffold(
        key: scaffoldKey,
        body: SingleChildScrollView(
            child: Container(
                padding: EdgeInsets.all(16.0),
                color: Colors.white,
                height: height,
                child: Form(
                  key: formKey,
                  autovalidate: _flag,
                  child: Column(
                    children: [
                      const SizedBox(height: 70),
                      const FlutterLogo(size: 150),
                      const SizedBox(height: 30),
                      TextFormField(
                          decoration: InputDecoration(
                              labelText: '手机号', border: OutlineInputBorder()),
                          validator: (val) =>
                              val.length != 11 ? '请输入正确的手机号' : null,
                          onSaved: (val) => _phone = val,
                          keyboardType: TextInputType.phone),
                      const SizedBox(height: 10.0),
                      TextFormField(
                        decoration: InputDecoration(
                            labelText: '密 码', border: OutlineInputBorder()),
                        validator: (val) => val.length < 6 ? '密码太短' : null,
                        onSaved: (val) => _password = val,
                        obscureText: true,
                      ),
                      const SizedBox(height: 10.0),
                      LoadingButton(
                        onPressed: () => _submit(appBloc),
                        backgroundColor: Colors.blueAccent,
                        buttonText: Text(
                          "登 录",
                          style: TextStyle(color: Colors.white),
                        ),
                        textColor: Colors.white,
                        loading: _loading,
                      ),
                      FlatButton(
                          onPressed: () => appBloc.addEvent(AppEvent.register),
                          child: Text("注 册")),
                    ],
                  ),
                ))));
  }
}
